package com.hk.core.autoconfigure.data.jpa;

import com.hk.commons.util.SnowflakeProperties;
import com.hk.core.authentication.api.SecurityContext;
import com.hk.core.data.jpa.BaseJpaRepositoryFactoryBean;
import com.hk.core.data.jpa.repository.BaseJpaRepository;
import com.hk.core.data.orm.aspect.OptimisticLockInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * <p>
 * JpaAutoConfiguration
 * </p>
 * <p>
 * EnableJpaRepositories
 * basePackages 指定扫描包，所有 repository 都必须放在指定的目录下
 * </p>
 *
 * @author kevin
 * @date 2018-06-07 13:07
 */
@EnableJpaAuditing
@AutoConfiguration
@EnableAspectJAutoProxy(exposeProxy = true)
@EnableConfigurationProperties(value = {SnowflakeProperties.class})
@ConditionalOnClass(BaseJpaRepository.class)
@EnableJpaRepositories(basePackages = {"com.hk.**.repository.jpa", "com.xzxx.**.repository.jpa"}, repositoryFactoryBeanClass =
        BaseJpaRepositoryFactoryBean.class)
public class JpaAutoConfiguration {

    /**
     * 这里的 Order 必须为1，表示在事务层面进行拦截
     */
    @Bean
    @Order(1)
    public OptimisticLockInterceptor optimisticLockInterceptor() {
        return new OptimisticLockInterceptor();
    }

    @Bean
    @ConditionalOnClass(value = {SecurityContext.class})
    @ConditionalOnBean(value = {SecurityContext.class})
    public EnableFilterAspect enableFilterAspect(SecurityContext securityContext) {
        return new EnableFilterAspect(securityContext);
    }

}
